import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import CreateApiDto from '../dto/CreateResourceDto';
import LRoleResourceRepository from '../repository/l_role_resource.repository';
import ResourceRepository from '../repository/resource.repository';
import { In } from 'typeorm';
import RoleRepository from '../repository/role.repository';

@Injectable()
export default class ResourceService {
  constructor(
    @InjectRepository(RoleRepository)
    private roleRepository: RoleRepository,
    @InjectRepository(ResourceRepository)
    private resourceRepoitory: ResourceRepository,
    @InjectRepository(LRoleResourceRepository)
    private lRoleResourceRepository: LRoleResourceRepository,
  ) {}

  async getResourceByKey(resourceKeys: string[]) {
    return await this.resourceRepoitory.find({
      where: { keyword: In(resourceKeys) },
    });
  }

  async create(api: CreateApiDto) {
    const apiEntity = await this.resourceRepoitory.save(
      this.resourceRepoitory.create({
        keyword: api.keyword,
        name: api.name,
        describe: api.describe,
      }),
    );
    return apiEntity.id;
  }

  async getResourceKeysByRoleKeys(roleKeys: string[]) {
    const roleIds = await this.roleRepository
      .find({
        where: { keyword: In(roleKeys) },
      })
      .then((roles) => roles.map((role) => role.id));
    const resourceIds =
      await this.lRoleResourceRepository.getResourceIdsByRoleIds(roleIds);
    const resourceKeys = await this.resourceRepoitory
      .find({
        where: { id: In(resourceIds) },
      })
      .then((resources) => resources.map((resource) => resource.keyword));
    return resourceKeys;
  }

  async getResourceIdsByRoleIds(roleIds: string[]) {
    return await this.lRoleResourceRepository.getResourceIdsByRoleIds(roleIds);
  }
}
